require 'digest/sha1'
class Complaint < ActiveRecord::Base
  belongs_to :user
  belongs_to :category
  belongs_to :sub_category
  has_many :urls, :dependent=>:destroy
  has_many :images, :dependent=>:destroy
  has_and_belongs_to_many :tags
  has_and_belongs_to_many :companies

  #validates_presence_of :user_id
  validates_presence_of :title
  validates_presence_of :description
  validates_presence_of :category_id

  after_update :save_urls
  after_update :save_images
  after_update :save_user

  def self.recent
    find(:all,:limit=>4,:order=>"created_at DESC")
  end

  def new_url_attributes=(url_attributes)
    url_attributes.each do |attributes|
      urls.build(attributes) unless attributes.empty?

    end
  end
  
  def existing_url_attributes=(url_attributes)
    urls.reject(&:new_record?).each do |url|
      attributes=url_attributes[url.id.to_s]
      if attributes
        url.attributes=attributes
      else
        urls.delete(url)
      end
    end
  end

  def save_urls
    urls.each do |url|
      url.save(false)
    end
  end

  def new_images=(project_images)
    project_images.each do |pimage|
      images.build(pimage) unless pimage.empty?
    end
  end

  def existing_images=(image_attributes)
    images.reject(&:new_record?).each do |image|
      attributes=image_attributes[image.id.to_s]
      if attributes
        image.attributes=attributes
      else
        images.delete(image)
      end
    end
  end

  def save_images
    images.each do |image|
      image.save(false)
    end
  end

  def new_complaint_user=(email_attribute)
    user_attributes={:login=>'default_user',:password=>'password123',:password_confirmation=>'password123'}
    user_attributes=user_attributes.merge(email_attribute)
    build_user(user_attributes)
  end
  
  def all_tags=(tag_ids)
    tags.clear
    tags << Tag.find(tag_ids)  
  end

  def all_companies=(comp_ids)
    companies.clear
    companies << Company.find(comp_ids)
  end


  def save_user
    user.save(false)
  end

  def week
      self.created_at.strftime('%W')
  end

end
